package com.cxso.example.sdk.http.core;


import com.cxso.example.sdk.domain.Result;
import com.cxso.example.sdk.http.base.AuthToken;
import com.cxso.example.sdk.http.base.ClientInfo;
import com.cxso.example.sdk.http.base.HttpMethod;
import com.cxso.example.sdk.http.cache.GenericCache;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class LoginClient extends AbstractClient {

    public LoginClient(ClientInfo clientInfo) {
        super(clientInfo);
    }

    protected ExecuteClient login(ClientInfo clientInfo, String path, String clientId, String clientSecret) {
        if (clientId == null || clientSecret == null) {
            throw new RuntimeException("用户令牌未指定");
        }
        String token = GenericCache.get(clientId, clientSecret);
        if (token == null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("clientId", clientId);
            hashMap.put("clientSecret", clientSecret);
            hashMap.put("productClientId", clientInfo.getProductClientId());
            String result = rpcInvoke(HttpMethod.POST, path, hashMap, null, false);
            ResultResolver resultResolver = new ResultResolver(clientInfo, result);
            Result<AuthToken> loginResult = resultResolver.toEntity(AuthToken.class);
            if (loginResult.isFail()) {
                throw new RuntimeException(loginResult.getMsg());
            }
            AuthToken data = loginResult.getData();
            Date expire = data.getExpire();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(expire);
            calendar.add(Calendar.HOUR_OF_DAY, -6);
            data.setExpire(calendar.getTime());
            GenericCache.cache(clientId, clientSecret, data);
        }
        return new ExecuteClient(clientInfo);
    }

}
